<template>
  <div class="department-container">
    <div class="app-container">
      <!-- 具体页面结构 -->
      <page-tools :title="`共有${total}条数据`">
        <template #left>
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('import_excel')" -->
          <el-button
            v-allow="'import_excel'"
            type="warning"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('export_excel')" -->
          <el-button
            v-allow="'export_excel'"
            type="danger"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <el-table :data="employees" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像" style="text-algin:center;">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="workNumber" sortable label="工号" />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" sortable label="入职时间" />
          <!-- <el-table-column prop="enableState" label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <!-- 跳转到详情页需要拿数据，跳转路由传入id -->
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="pForm.page"
            :page-sizes="[5, 10, 15]"
            :page-size="pForm.size"
            layout="sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="添加部门"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <emp-dialog ref="empDialog" @success="hSuccess" />
    </el-dialog>
    <el-dialog title="分配角色" :visible.sync="showDialogRole">
      <assign-rloe ref="AssignRloe" :cur-id="curId" @success="hSuccessRole" />
    </el-dialog>

  </div>
</template>

<script>
import AssignRloe from './AssignRloe.vue'
import EmpDialog from '@/views/employees/EmpDialog.vue'
import EmployeeEnum from '@/constant/employees'
import { getEmployees, delEmployeeAPI } from '@/api/employee'
import { TYPE_MAP } from '@/constant/index'
export default {
  components: {
    EmpDialog,
    AssignRloe
  },
  data() {
    return {
      employees: [],
      total: 0,
      pForm: {
        page: 1,
        size: 5
      },
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.initEmployees()
  },
  methods: {
    // 子组件成功分配角色
    hSuccessRole() {
      this.showDialogRole = false
      this.$message.success('保存成功')
    },
    // 点击分配角色按钮
    hAssignRole(id) {
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        this.$refs.AssignRloe.getUserDetail()
      })
    },
    // 格式化数据
    formDate(arr) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // excel表的表头
      const header = Object.keys(arr[0]).map(ele => map[ele])
      // 表格数据
      const data = arr.map(ele => {
        ele['formOfEmployment'] = TYPE_MAP[ele.formOfEmployment]
        return Object.values(ele)
      })
      return { header, data }
    },
    // exceil导出
    async handleDownload() {
      const res = await getEmployees(this.pForm)
      // 这个文件初始不会加载进来，@/vendor/Export2Excel
      // 点击按钮，执行回调，就会去加载这个文件
      // .then()当文件读入完成之后，做....
      import('@/vendor/Export2Excel').then(excel => {
        // // 准备数据
        // const tHeader = ['Id', 'Title', 'Author', 'Readings', 'Date']
        // const filterVal = ['id', 'title', 'author', 'pageviews', 'display_time']
        // const list = this.list
        // const data = this.formatJson(filterVal, list)

        const { header, data } = this.formDate(res.data.rows)
        // 生成excel
        excel.export_json_to_excel({
          header,
          data,
          // filename: this.filename,
          // autoWidth: this.autoWidth,
          // bookType: this.bookType,
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
        // this.downloadLoading = false
      })
    },
    // 子组件表单提交成功，子向父抛出事件
    hSuccess() {
      // 关闭dialog
      this.showDialog = false
      // 重新请求数据
      this.initEmployees()
    },
    hClose() {
      this.$refs.empDialog.resetForm()

      // this.$nextTick(() => {
      //   this.$refs.empDialog.resetForm()
      // })
    },
    // 删除
    async doDel(id) {
      try {
        await delEmployeeAPI(id)
        this.$message.success('删除成功')
        if (this.employees.length === 1) {
          (this.pForm.page > 1) && this.pForm.page--
        }
        // 删除成功更新数据
        this.initEmployees()
      } catch (err) {
        console.log('', err)
      }
    },
    // 用户点击删除按钮
    hDel(id) {
      this.$confirm('确定删除？', '系统提示').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    handleSizeChange(val) {
      this.pForm.size = val
      this.pForm.page = 1
      this.initEmployees()
    },
    handleCurrentChange(val) {
      this.pForm.page = val
      this.initEmployees()
    },
    // 格式化数据
    format(type) {
      /*  const item = EmployeeEnum.hireType.find((ele) => ele.id === type)
      if (item) {
        return item.value
      } else {
        return '未知'
      } */
      const index = EmployeeEnum.hireType.findIndex(ele => ele.id === type)
      if (index !== -1) {
        return EmployeeEnum.hireType[index].value
      } else {
        return '未知'
      }
    },
    async initEmployees() {
      try {
        const res = await getEmployees(this.pForm)
        console.log('res', res)
        // 保存数据
        this.employees = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log('', err)
      }
    }
  }
}
</script>
